<!-- Content Header (Page header) -->
<section class="content-header">
	<h1>SQL监控</h1>
	<ol class="breadcrumb">
		<li><a href="#"><i class="fa fa-dashboard"></i>SQL监控</a></li>
		<li><a href="#"></i>SQL监控</a></li>
	</ol>
</section>
<!-- Main content -->
<section id="container" class="content">
	<div class="row">
		<div class="col-md-12">
			<div class="box box-primary">

				<div class="box-header">
				 <form action="" id="query_Form">
				 		<input name="begin" id="begin" type="hidden"/>
				 		<input name="end" id="end" type="hidden"/>
				 		<div class="row">
							<div class="col-xs-3">
								<label for="mycatName">查询条件:</label>
								<div class="form-group">
									<select onchange="datasouce_change()" name="ds" id="datasource" class="form-control" style="width: 200px;">
		            				</select>
								</div>
							</div>
							<div class="col-xs-3">
								<div class="form-group">
									<label for="username">用户:</label> <input id="username"
										type="text" name="username" class="form-control"
										placeholder="用户" validateType="lengthRange-1-100">
								</div>
							</div>
<!-- 							<div class="col-xs-8">
								<div class="form-group">
									 <button class="btn btn-primary"  onclick="exportcsv()" type="button">导出CSV</button>
								</div>
							</div> -->
							<div class="col-xs-6">
								<div class="form-group">
								<label for="mycatName">区间查询:</label>
									<div class="input-group">
										<div class="input-group-addon">
											<i class="fa fa-clock-o"></i>
										</div>
										<input type="text" class="form-control pull-right"
											id="reservationtime">
									</div>
								</div>
							</div>
						</div>


		         </form>
				</div>
							<div class="box-footer">
					<div class="form-group">
						<div class="col-lg-offset-5 col-lg-2">
							<button class="btn btn-primary" onclick="queryForm('query_Form')">查询</button>
							<button class="btn btn-primary" onclick="resetBtn('query_Form')">重置</button>
						</div>
					</div>
				</div>
				<div class="box-body">
					<div>
						<table id="table"></table>
						<div style="text-align: right;">
							<div id="paginator"></div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	</div>
</section>
<!-- /.content -->

<!-- /.content -->
<div class="modal fade" id="sqlModal" tabindex="-1" role="dialog"
	aria-labelledby="myModalLabel">
	<div class="modal-dialog modal-lg">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"
					aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
				<h4 class="modal-title" id="mysqlexplain">SQL详情</h4>
			</div>
			<div class="modal-body" id="sqlDetail">

			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
			</div>
		</div>
	</div>
</div>

<script type="text/javascript">
   $.AdminLTE.boxWidget.activate();
	var sqlId = "";
</script>

<script type="text/javascript">
/**
 * 时间原型增加一个 format 函数
 */
Date.prototype.format = function(fmt) {
  var o = {
    "M+" : this.getMonth()+1,                 //月份
    "d+" : this.getDate(),                    //日
    "h+" : this.getHours(),                   //小时
    "m+" : this.getMinutes(),                 //分
    "s+" : this.getSeconds(),                 //秒
    "q+" : Math.floor((this.getMonth()+3)/3), //季度
    "S"  : this.getMilliseconds()             //毫秒
  };
  if(/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  for(var k in o)
    if(new RegExp("("+ k +")").test(fmt))
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt;
}
var datasouce_change = function(){
	var daterange = $('#reservationtime').val().split('~');
	var begin = daterange[0].trim();
	var end = daterange[1].trim();
	$('#begin').val(begin);
	$('#end').val(end);
}


//Date range picker with time picker
$('#reservationtime').daterangepicker(
		{
			maxDate : moment(), //最大时间
			showDropdowns : true,
			showWeekNumbers : false, //是否显示第几周
			timePicker : true, //是否显示小时和分钟
			timePickerIncrement : 60, //时间的增量，单位为分钟
			timePicker12Hour : false, //是否使用12小时制来显示时间
			ranges : {
				//'最近1小时': [moment().subtract('hours',1), moment()],
				'今日' : [ moment().startOf('day'), moment() ],
				'昨日' : [
						moment().subtract('days', 1).startOf(
								'day'),
						moment().subtract('days', 1).endOf(
								'day') ],
				'最近7日' : [ moment().subtract('days', 6),
						moment() ],
				'最近30日' : [ moment().subtract('days', 29),
						moment() ]
			},
			opens : 'right', //日期选择框的弹出位置
			format : 'YYYY-MM-DD HH:mm', //控件中from和to 显示的日期格式
			separator : ' to ',
			locale : {
				applyLabel : '确定',
				cancelLabel : '取消',
				fromLabel : '起始时间',
				toLabel : '结束时间',
				customRangeLabel : '自定义',
				daysOfWeek : [ '日', '一', '二', '三', '四', '五',
						'六' ],
				monthNames : [ '一月', '二月', '三月', '四月', '五月',
						'六月', '七月', '八月', '九月', '十月', '十一月',
						'十二月' ],
				firstDay : 1
			}
		});


$("#reservationtime").on('apply.daterangepicker', function() {
	var daterange = $('#reservationtime').val().split('~');
	var begin = daterange[0].trim();
	var end = daterange[1].trim();
	$('#begin').val(begin);
	$('#end').val(end);
	queryForm('query_Form');
});

var Selected_Callback = function(target_select){
	  this.onSuccess=function(data){
			try {
				var j_obj = data;
				if (j_obj.success) {
					var length = j_obj.rows.length;
					for(var i=0;i<length;i++){
						var mycatName = j_obj.rows[i].mycatName;
						$("#"+target_select).append("<option value=\""+ mycatName+"\">"+ mycatName+"</option>");
						if(i==0){
							datasouce_change();
						}
					}
				}
			} catch (e) {
				alert("异常!")
			}
		};
		this.onFail = function(jqXHR, textStatus, errorThrown){
		};
};

var exportcsv =function(){
	var url = "./dispatcherAction/exportCSV.do?service=showService&method=sql&ds="+$('#datasource').val()+"&fileName=sql";
	window.location = url;
}

var initDataSouce = function(){
	var rainbow = new Rainbow();
	rainbow.setService("mycatService");
	rainbow.setMethod("query");
	rainbowAjax.query(rainbow, new Selected_Callback("datasource"));
};


var viewMysql = function(id) {
	sqlId = id;
	$('#sqlDetail').load('./page/sql/sqldetail.html?v=' + Math.random());
	$('#sqlModal').modal({
		show : true
	});
};

$(document).ready(function() {
	initDataSouce();
		    var cols = [
		                 {
							title : '操作',
							name : 'operation',
							width : 100,
							align : 'center',
							renderer : function(val, item, rowIndex) {
								//return '<button class="btn btn-danger btn-xs" onclick=explainMysql12("'+item+'")>删除</button>&nbsp;';
								return '<button  class="btn btn-primary btn-xs modify" onclick=viewMysql(\"' + item.SID +'\")>详情</button>';
							}
						},
						{ title:'ID', name:'ID' ,width:100, align:'left', sortable:true },
						{ title:'数据源', name:'DB_NAME' ,width:100, align:'left', sortable:true},
						{ title:'用户', name:'USER' ,width:80, align:'left', sortable:true},
						{ title:'IP', name:'IPAddr' ,width:150, align:'left', sortable:true},
				        { title:'SQL', name:'SQL' ,width:600, align:'left',
							renderer : function(val, item, rowIndex) {
								//return '<button class="btn btn-danger btn-xs" onclick=explainMysql12("'+item+'")>删除</button>&nbsp;';
								//alert(item.SQL.substring(0,10));
								var sql = item.SQL;
								return  sql.length >= 100 ? sql.substring(0,100) + "..." : sql;
							}},
						{ title:'耗时(ms)', name:'EXECUTE_TIME' ,width:100, align:'left', sortable:true, type:'number'},
				        { title:'执行时间', name:'START_TIME' ,width:160, align:'left', sortable:true,
				        	renderer: function(val){
				        		console.debug( "vv:" + val);
				        		var d = new Date(val).format("yyyy-MM-dd hh:mm:ss");;
				        		return d;
				        	} }

			    ];
	mmgrid  = $('#table').mmGrid({
	        indexCol: true,
	        height: '400',
	        indexColWidth: 35,
	        cols: cols,
	        url: './dispatcherAction/queryByMMGrid.do?service=showService&method=sql',
	        params: function(){
	        	var daterange = $('#reservationtime').val().split('~');
	        	var begin = daterange[0].trim();
	        	var end = daterange[1].trim();
	        	if ($('#username').val().length>0){
	        		return {ds:$('#datasource').val(),begin:begin,end:end,username:$('#username').val()};
	        	}else{
	        		return {ds:$('#datasource').val(),begin:begin,end:end};
	        	}

	        	//return $('#query_Form').serializeJson();
	        },
	        method: 'post',
	        root: 'items',
	        plugins:[
	                 //配置当前grid默认的分页大小以及总记录数的名称
	                	$('#paginator').mmPaginator({limit:20, totalCountName:'totalCount'})
	               ]
	    });
});

</script>
